package com.yuyou.fn.controller;

import com.github.wens.mybatisplus.plugins.Page;
import com.google.common.base.Joiner;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.Principals;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.crm.entity.CrmCommunicateHistory;
import com.yuyou.fn.crm.entity.CrmStudentCommunicate;
import com.yuyou.fn.crm.service.ICrmCommunicateHistoryService;
import com.yuyou.fn.crm.service.ICrmStudentCommunicateService;
import com.yuyou.fn.crm.vo.*;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.platform.permission.DataPermission;
import com.yuyou.fn.report.entity.MergeStudentRegDetail;
import com.yuyou.fn.util.Excels;
import com.yuyou.fn.util.Webs;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by wens on 2018/02/05.
 */
@Controller
@RequestMapping("/api/admin/communicate")
public class AdminCommunicateController extends ApiBaseController {

    @Resource
    private ICrmStudentCommunicateService crmStudentCommunicateService;

    @Resource
    private ICrmCommunicateHistoryService crmCommunicateHistoryService;

    @Resource
    private IBaseGradeService baseGradeService;

    @ApiOperation("家校沟通列表")
    @RequestMapping(value = "/studentCommunicatePage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CrmStudentCommunicate>> studentCommunicatePage(@ModelAttribute StudentCommunicateQueryVo studentCommunicateQueryVo, HttpServletRequest request, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {
        CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo = new CrmStudentCommunicateQueryVo();
        BeanUtils.copyProperties(crmStudentCommunicateQueryVo, studentCommunicateQueryVo);
        Principals.Principal principals = Principals.get();
        if (principals == null) {
            throw new BusException("登录后再查询");
        }
        crmStudentCommunicateQueryVo.setSeniorId(principals.id);
        Page<CrmStudentCommunicate> crmStudentCommunicatePage = crmStudentCommunicateService.findCommunicatePageByQueryVo(crmStudentCommunicateQueryVo, pageNo, pageSize);
        return ReturnResult.success(crmStudentCommunicatePage);
    }


    @ApiOperation("导出家校沟通列表")
    @RequestMapping(value = "/exportSeniorCommunicate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportSeniorCommunicate(@ModelAttribute StudentCommunicateQueryVo studentCommunicateQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo = new CrmStudentCommunicateQueryVo();
        BeanUtils.copyProperties(crmStudentCommunicateQueryVo, studentCommunicateQueryVo);
        Principals.Principal principals = Principals.get();
        if (principals == null) {
            throw new BusException("登录后再查询");
        }
        crmStudentCommunicateQueryVo.setSeniorId(principals.id);
        Webs.writeExcel(request, response, crmStudentCommunicateService.exportStudentCommunicate(crmStudentCommunicateQueryVo), "家校沟通列表");
        return ReturnResult.success("ok");
    }

    @ApiOperation("家校沟通数据下载")
    @RequestMapping(value = "/exportStudentCommunicate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportStudentCommunicate(@ModelAttribute StudentCommunicateQueryVo studentCommunicateQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo = new CrmStudentCommunicateQueryVo();
        BeanUtils.copyProperties(crmStudentCommunicateQueryVo, studentCommunicateQueryVo);
        Principals.Principal principals = Principals.get();
        if (principals == null) {
            throw new BusException("登录后再查询");
        }
        crmStudentCommunicateQueryVo.setSeniorId(principals.id);
        List<CrmStudentCommunicate> crmStudentCommunicateList = crmStudentCommunicateService.findCommunicateListByQueryVo(crmStudentCommunicateQueryVo);
        List<BaseGrade> baseGradeList = baseGradeService.findAllFromCache();
        Map<Long, BaseGrade> gradeMap = BeanUtils.toMap(baseGradeList, "gradeId");
        XSSFWorkbook sxssfWorkbook = studentCommunicate2ExcelForImput(crmStudentCommunicateList, gradeMap);
        Webs.writeExcel(request, response, sxssfWorkbook, "家校沟通导入");
        return ReturnResult.success("ok");
    }

    public XSSFWorkbook studentCommunicate2ExcelForImput(List<CrmStudentCommunicate> crmStudentCommunicateList, Map<Long, BaseGrade> gradeMap) {
        String sheetName = "家校沟通导入";
        XSSFWorkbook excel = new XSSFWorkbook();
        XSSFSheet sheet = excel.createSheet(sheetName);
        XSSFRow firstRow = sheet.createRow(0);
        //设置沟通日期的列宽
        int with = 10;
        sheet.setColumnWidth(13, 256*with+184);
        String[] titles = new String[]{"唯一ID(不可更改)", "学生姓名", "学生电话", "学号", "报读期数", "生源类型", "报读年级", "段次", "报读业务组", "班主任", "沟通形式", "续读意愿", "是否重点关注", "沟通日期", "下次沟通日期", "沟通内容"};
        for (int i = 0; i < titles.length; i++) {
            firstRow.createCell(i).setCellValue(titles[i]);
        }
        int rowNum = 1;
        Excels.createDict(excel, "沟通形式", Arrays.asList("电话拨入", "电话拨出", "面谈", "微信/QQ", "其他"));
        Excels.createDict(excel, "续读意愿", Arrays.asList("强烈", "一般", "无意愿"));
        Excels.createDict(excel, "是否重点关注", Arrays.asList("是", "否"));
        Date date = TimeUtils.nowDate();
        if (crmStudentCommunicateList != null) {
            CellStyle cellStyle = excel.createCellStyle();
            DataFormat dataFormat = excel.createDataFormat();
            cellStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd"));
            for (CrmStudentCommunicate crmStudentCommunicate : crmStudentCommunicateList) {
                Excels.addFormulaListConstraint(sheet, "沟通形式", rowNum, 1024 * 5, 10, 10);
                Excels.addFormulaListConstraint(sheet, "续读意愿", rowNum, 1024 * 5, 11, 11);
                Excels.addFormulaListConstraint(sheet, "是否重点关注", rowNum, 1024 * 5, 12, 12);

                int cellNum = 0;

                XSSFRow row = sheet.createRow(rowNum++);

                XSSFCell cell = row.createCell(cellNum++);
                cell.setCellValue(crmStudentCommunicate.getStudentCommunicateId().toString());

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getStudentName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getStudentPhoneNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getStudentNo()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getPeriodName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmStudentCommunicate.getStudentState() == null ? "" : crmStudentCommunicate.getStudentState() == 0 ? "新生" : crmStudentCommunicate.getStudentState() == 1 ? "老生" : "续读生");

                cell = row.createCell(cellNum++);
                cell.setCellValue(gradeMap.get(crmStudentCommunicate.getGradeId()) == null ? "" : gradeMap.get(crmStudentCommunicate.getGradeId()).getGradeName());

                cell = row.createCell(cellNum++);
                cell.setCellValue(crmStudentCommunicate.getSegmentNo() == null ? "" : crmStudentCommunicate.getSegmentNo().toString());

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getBusTeamName()));

                cell = row.createCell(cellNum++);
                cell.setCellValue(StringUtils.defaultString(crmStudentCommunicate.getSeniorName()));

                cell = row.createCell(cellNum++);

                cell = row.createCell(cellNum++);

                cell = row.createCell(cellNum++);

                cell = row.createCell(cellNum++);
                cell.setCellValue(date);
                cell.setCellStyle(cellStyle);

                cell = row.createCell(cellNum++);
                cell.setCellStyle(cellStyle);

                cell = row.createCell(cellNum++);
            }
        }
        return excel;
    }

    @ApiOperation("家校沟通数据导入")
    @RequestMapping(value = "/importStudentCommunicate", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> importStudentCommunicate(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ImportParams params = new ImportParams();
        List<CrmCommunicateInputVo> importCourseClassVoList = ExcelImportUtil.importExcel(inputStream, CrmCommunicateInputVo.class, params);

        crmCommunicateHistoryService.saveCommunicateHistoryBatch(importCourseClassVoList);
        return ReturnResult.success("ok");
    }


    @ApiOperation("预约人数，重点人数")
    @RequestMapping(value = "/countCommunicateNum", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Map<String, Integer>> studentCommunicatePage(@RequestParam("busTeamIds") String busTeamIds, @RequestParam("periodIds") String periodIds, HttpServletRequest request) throws IOException {

        Principals.Principal principals = Principals.get();
        if (principals == null) {
            throw new BusException("登录后再查询");
        }
        CrmStudentCommunicateQueryVo crmStudentCommunicateQueryVo = new CrmStudentCommunicateQueryVo();
        crmStudentCommunicateQueryVo.setSeniorId(principals.id);
        crmStudentCommunicateQueryVo.setBusTeamIds(busTeamIds);
        crmStudentCommunicateQueryVo.setPeriodIds(periodIds);
        crmStudentCommunicateQueryVo.setNextCommunicateDate(Utils.formatDate(TimeUtils.nowDate(), "yyyy-MM-dd"));
        Long todayCommunicateNum = crmStudentCommunicateService.countCommunicateByQueryVo(crmStudentCommunicateQueryVo);

        crmStudentCommunicateQueryVo.setNextCommunicateDate(null);
        crmStudentCommunicateQueryVo.setFocusOn(1);
        Long focusOnCommunicateNum = crmStudentCommunicateService.countCommunicateByQueryVo(crmStudentCommunicateQueryVo);

        Map<String, Integer> map = new HashMap<>();
        map.put("todayCommunicateNum", todayCommunicateNum.intValue());
        map.put("focusOnCommunicateNum", focusOnCommunicateNum.intValue());
        return ReturnResult.success(map);
    }


    @ApiOperation("沟通需填写的报名信息")
    @RequestMapping(value = "/findStudentRegByCommunicateId", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<MergeStudentRegDetail>> findStudentRegByCommunicateId(@RequestParam("studentCommunicateId") long studentCommunicateId, HttpServletRequest request) throws IOException {
        List<MergeStudentRegDetail> studentRegList = crmStudentCommunicateService.findStudentRegByCommunicateId(studentCommunicateId);
        return ReturnResult.success(studentRegList);
    }


    @ApiOperation("沟通登记")
    @RequestMapping(value = "/communicationSave", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> communicationSave(@ModelAttribute CrmCommunicateHistorySaveVo crmCommunicateHistorySaveVo) throws IOException {

        crmCommunicateHistoryService.saveCommunicateHistory(crmCommunicateHistorySaveVo);

        return ReturnResult.success("ok");
    }

    @ApiOperation("单个学生沟通历史")
    @RequestMapping(value = "/studentCommunicateHistory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<List<CrmCommunicateHistory>> studentCommunicateHistory(@ModelAttribute CrmCommunicateHistoryQueryVo crmCommunicateHistoryQueryVo, HttpServletRequest request) throws IOException {
        if (crmCommunicateHistoryQueryVo.getStudentId() == null) {
            throw new BusException("请传入学生id");
        }
        List<CrmCommunicateHistory> crmCommunicateHistoryList = crmCommunicateHistoryService.findCommunicateHistoryList(crmCommunicateHistoryQueryVo);

        return ReturnResult.success(crmCommunicateHistoryList);
    }


    @ApiOperation("沟通历史")
    @RequestMapping(value = "/communicateHistory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CrmCommunicateHistory>> communicateHistory(@ModelAttribute CrmCommunicateHistoryQueryVo crmCommunicateHistoryQueryVo, HttpServletRequest request, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize) {
        if (null == crmCommunicateHistoryQueryVo.getBusTeamIds()) {
            DataPermission dataPermission = getDataPermission(request);
            List<Long> busTeamIds = dataPermission.getBusTeamIds();
            if (null == busTeamIds || busTeamIds.size() == 0) {
                throw new BusException("该账号没有分配业务组权限！");
            }
            crmCommunicateHistoryQueryVo.setBusTeamIds(Joiner.on(",").join(busTeamIds));
        }
        Page<CrmCommunicateHistory> page = crmCommunicateHistoryService.findCommunicateHistoryPage(crmCommunicateHistoryQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }


    @ApiOperation("导出沟通历史")
    @RequestMapping(value = "/exportCommunicateHistory", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportstudentCommunicate(@ModelAttribute CrmCommunicateHistoryQueryVo crmCommunicateHistoryQueryVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (null == crmCommunicateHistoryQueryVo.getBusTeamIds()) {
            DataPermission dataPermission = getDataPermission(request);
            List<Long> busTeamIds = dataPermission.getBusTeamIds();
            if (null == busTeamIds || busTeamIds.size() == 0) {
                throw new BusException("该账号没有分配业务组权限！");
            }
            crmCommunicateHistoryQueryVo.setBusTeamIds(Joiner.on(",").join(busTeamIds));
        }
        Webs.writeExcel(request, response, crmCommunicateHistoryService.exportCommunicateHistory(crmCommunicateHistoryQueryVo), "沟通历史");
        return ReturnResult.success("ok");
    }


    @ApiOperation("沟通情况")
    @RequestMapping(value = "/communicateSituation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Page<CommunicateSituationVo>> communicateSituation(@ApiParam("gradeId") Long gradeId,
                                                                           @ApiParam("segmentNo") Integer segmentNo,
                                                                           @ApiParam("班主任业务组ids") @RequestParam(value = "seniorBusTeamIds", required = false) String seniorBusTeamIds, @ApiParam("班主任名称") @RequestParam(value = "seniorName", required = false) String seniorName, @RequestParam(value = "periodIds", required = false) String periodIds,
                                                                           @RequestParam("pageNo") int pageNo,
                                                                           @RequestParam("pageSize") int pageSize,
                                                                           HttpServletRequest request) {
        CommunicateSituationQueryVo communicateSituationQueryVo = new CommunicateSituationQueryVo();
        communicateSituationQueryVo.setPeriodIds(Utils.toLongIds(periodIds));
        if (null == seniorBusTeamIds) {
            DataPermission dataPermission = getDataPermission(request);
            List<Long> busTeamIds = dataPermission.getBusTeamIds();
            if (null == busTeamIds || busTeamIds.size() == 0) {
                throw new BusException("该账号没有分配业务组权限！");
            }
            communicateSituationQueryVo.setSeniorBusTeamIds(busTeamIds);
        } else {
            communicateSituationQueryVo.setSeniorBusTeamIds(Utils.toLongIds(seniorBusTeamIds));
        }
        communicateSituationQueryVo.setSeniorName(seniorName);
        communicateSituationQueryVo.setGradeId(gradeId);
        communicateSituationQueryVo.setSegmentNo(segmentNo);
        Page<CommunicateSituationVo> page = crmStudentCommunicateService.findCommunicateSituation(communicateSituationQueryVo, pageNo, pageSize);
        return ReturnResult.success(page);
    }

    @ApiOperation("导出沟通情况")
    @RequestMapping(value = "/exportCommunicateSituation", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ReturnResult<Void> exportCommunicateSituation(@ApiParam("gradeId") Long gradeId,
                                                         @ApiParam("segmentNo") Integer segmentNo,
                                                         @ApiParam("班主任业务组ids") @RequestParam(value = "seniorBusTeamIds", required = false) String seniorBusTeamIds, @ApiParam("班主任名称") @RequestParam(value = "seniorName", required = false) String seniorName, @RequestParam(value = "periodIds", required = false) String periodIds, HttpServletRequest request, HttpServletResponse response) throws IOException {
        CommunicateSituationQueryVo communicateSituationQueryVo = new CommunicateSituationQueryVo();
        communicateSituationQueryVo.setPeriodIds(Utils.toLongIds(periodIds));
        if (null == seniorBusTeamIds) {
            DataPermission dataPermission = getDataPermission(request);
            List<Long> busTeamIds = dataPermission.getBusTeamIds();
            if (null == busTeamIds || busTeamIds.size() == 0) {
                throw new BusException("该账号没有分配业务组权限！");
            }
            communicateSituationQueryVo.setSeniorBusTeamIds(busTeamIds);
        } else {
            communicateSituationQueryVo.setSeniorBusTeamIds(Utils.toLongIds(seniorBusTeamIds));
        }
        communicateSituationQueryVo.setSeniorName(seniorName);
        communicateSituationQueryVo.setGradeId(gradeId);
        communicateSituationQueryVo.setSegmentNo(segmentNo);
        Webs.writeExcel(request, response, crmStudentCommunicateService.exportCommunicateSituation(communicateSituationQueryVo), "沟通情况");
        return ReturnResult.success("ok");
    }


}
